<template>
  <el-dialog @close="closeDialog" :title="form.id ? $t('common.editBtn') : $t('common.addBtn')" v-model="visible"
    :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item prop="shopId" :label="$t('ProdGroupReference.shopId')">
            <ShopSelect @change="changeShopId" v-model="form.shopId" />

          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item prop="groupId" :label="$t('ProdGroupReference.groupId')">
            <el-input v-model="form.groupId" disabled :placeholder="$t('ProdGroup.selectGroupid')" clearable
              show-word-limit />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item prop="prodId" :label="$t('ProdGroupReference.prodId')">
            <el-button @click="openSelect">{{ $t('Video.select') }}</el-button>

            <!-- <el-input v-model="form.prodId" :placeholder="$t('ProdGroupReference.inputProdIdTip')" clearable
              show-word-limit /> -->
          </el-form-item>
          <div class="ML-20">

            <el-table :data="activeProdIdArr" border>
              <el-table-column prop="id" :label="$t('Video.prodId')" show-overflow-tooltip />
              <el-table-column prop="name" :label="$t('Video.prodName')" show-overflow-tooltip />
            </el-table>
          </div>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item prop="state" :label="$t('ProdGroupReference.state')">

            <el-switch :active-value="1" v-model="form.state" :inactive-value="0"></el-switch>
            <!-- <el-input v-model="form.state" :placeholder="$t('ProdGroupReference.inputStateTip')" clearable
              show-word-limit /> -->
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
      </span>
    </template>
    <ProdSelect ref="selsectREF" :getPage="getPage" :tableOption="[
      {
        prop: 'id', label: 'id'
      },
      {
        prop: 'name', label: $t('Video.prodName')
      }]" searchName="search" @submit="submitSelectFn" :shopId="form.shopId" />
  </el-dialog>
</template>

<script setup lang="ts" name="ProdGroupReferenceDialog">
import { useMessage } from "/@/hooks/message";
import { getPage } from "/@/api/bizs/Prod";

import { getObj, addObj, putObj, batchAddAPI } from '/@/api/bizs/ProdGroupReference'
const emit = defineEmits(['refresh']);

// 定义i18n
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

// 定义字典
import { useDict } from '/@/hooks/dict';
const { common_state_enable } = useDict('common_state_enable')
const ShopSelect = defineAsyncComponent(() => import("/@/components/ShopSelect/index.vue"))
const ProdSelect = defineAsyncComponent(() => import("/@/components/ProdSelect/index.vue"))
const activeProdIdArr = ref<{ id: string | number }[]>([]) //  选择的产品id
// 定义i18n

// 定义变量内容
const visible = ref(false)
const loading = ref(false)
const dataFormRef = ref();
const selsectREF = ref()
// 提交表单数据
const form = reactive({
  id: '',
  shopId: '',
  groupId: '',
  prodId: '',
  state: '',
});

// 定义校验规则
import { rule } from '/@/utils/validate';
const dataRules = ref({
  shopId: [{ required: false, message: t('ProdGroupReference.inputShopIdTip'), trigger: 'blur' }],
  groupId: [{ required: true, message: t('ProdGroup.selectGroupid'), trigger: 'blur' }],
  prodId: [{ required: false, message: t('ProdGroupReference.inputProdIdTip'), trigger: 'blur' }],
  state: [{ required: false, message: t('ProdGroupReference.inputStateTip'), trigger: 'blur' }],
})

const changeShopId = () => {
  activeProdIdArr.value = []
}

const closeDialog = () => {
  activeProdIdArr.value = []
}

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.id = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取信息
  if (id) {
    form.id = id
    initFormData(id)
  }
};

const submitSelectFn = (selection: any) => {
  activeProdIdArr.value = selection
}

//  打开产品选择
const openSelect = () => {

  selsectREF.value.showFn(activeProdIdArr.value)
}


// 初始化表单
const initFormData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};

const setGroupIdFn = (groupId?: string | number) => {
  nextTick(() => {
    form.groupId = groupId

  })
}

// 提交表单
const onSubmit = async () => {


  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;

  if (activeProdIdArr.value.length == 0) {
    useMessage().error(t('ProdGroup.selectProdId'))
    return
  }

  let prodGroupReferenceList = activeProdIdArr.value.map((el: object) => {
    return {
      shopId: el.shopId,
      groupId: form.groupId,
      prodId: el.id
    }
  })
  let obj = {
    id: form.groupId,
    prodGroupReferenceList
  }
  try {
    loading.value = true;
    form.id ? await putObj(form) : await batchAddAPI(obj);
    useMessage().success(form.id ? t('common.editSuccessText') : t('common.addSuccessText'));
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 暴露变量
defineExpose({
  openDialog, setGroupIdFn
});
</script>
<style lang="scss" scoped>
.ML-20 {
  margin-left: 50px
}
</style>
